/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo;

import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author odeen
 */
public class DAO {

    private Context ctx;

    public DAO() throws NamingException {
        ctx = new InitialContext();
    }

    private UserTransaction getUserTransaction() throws NamingException {
        return (UserTransaction) ctx.lookup("java:comp/env/UserTransaction");
    }

    private EntityManager getEntityManager() throws NamingException {
        return (EntityManager) ctx.lookup("java:comp/env/persistence/LogicalName");
    }

    public Usuario buscarUsuario(String usuario, String clave) {
        Usuario resp = null;
        try {
            UserTransaction t = getUserTransaction();
            t.begin();
            EntityManager em = getEntityManager();
            Query consulta = em.createQuery("SELECT u FROM Usuario u WHERE u.nick=:usuario AND u.password=:clave");
            consulta.setParameter("usuario", usuario);
            consulta.setParameter("clave", MD5(clave));
            try {
                resp = (Usuario) consulta.getSingleResult();
            } catch (NoResultException e) {
                resp = null;
            }
            t.commit();
            return resp;
        } catch (Exception e) {
            Logger.getLogger("modelo.DAO").log(Level.SEVERE, "Error ", e);
            return null;
        }
    }

    public String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

    public List<Usuario> buscarTodosUsuarios() {
        List<Usuario> resp;
        try {
            UserTransaction t = getUserTransaction();
            t.begin();
            EntityManager em = getEntityManager();
            Query consulta = em.createQuery("SELECT u FROM Usuario u");
                resp = consulta.getResultList();
            t.commit();
            return resp;
        } catch (Exception e) {
            Logger.getLogger("modelo.DAO").log(Level.SEVERE, "Error ", e);
            return Collections.EMPTY_LIST;
        }
    }
}
